package com.weme.common.ext

import android.text.TextUtils
import androidx.media3.common.Player
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.weme.common.R
import com.weme.common.activity.CallActivity
import com.weme.common.activity.CallOperationType
import com.weme.common.dialog.PermissingDialog
import com.weme.common.manager.MessageHandler
import com.weme.common.util.*
import com.weme.common.view.PlayVideoView
import dev.kratos.api.cms_server.v1.CallConfig
import dev.kratos.api.im_server.v1.RefuseVideoRequest
import dev.kratos.api.user_server.v1.GetAlbumRequest
import dev.kratos.api.user_server.v1.Users
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class CallExt

// 初始化用户信息视图
fun CallActivity.initUserInfoView(user: Users) {
    val userInfo = getString(com.example.resources.R.string.user_info_format, user.nickname, user.age)
    getViewBind().tvName.text = userInfo
    val country = getCountryBean(user.countryCode)
    country?.let {
        getViewBind().imCountry.loadImage(it.countryFlag)
        getViewBind().tvLanguage.text = it.countryName
    }
    getViewMode().getAlbum(GetAlbumRequest.newBuilder().setUid(user.uid).build())
}

// 处理订阅信息
fun CallActivity.isSubscribeInfo() {
    if (isVip()) {
        getViewBind().countdownProgressBar.startCountdown {
            showToast(resources.getString(com.example.resources.R.string.call_now))
            onBackPressedCallback.handleOnBackPressed()
        }
        getViewBind().tvTip.text = String.format(resources.getString(com.example.resources.R.string.call_time_tip),retrieveCallConfig().normalCall)

    } else {
        countdownLongJob = CoroutineScope(Dispatchers.Main).launch {
            delay(delayMillis)
            callVideoReply?.apply {
                getViewMode().setCancelCall(channelName, this.user.uid)
                AgoraClient.getInstance().sendImCallMsg(this.user.uid.toString())
            }
            showToast(resources.getString(com.example.resources.R.string.call_now))
            finish()
        }
        getViewBind().smlTime.gone()
    }
}
var callConfig: CallConfig? = null


fun retrieveCallConfig(): CallConfig {
    if (callConfig == null || callConfig!!.normalIncomeTime == 0) { // 从 MMKV 中获取数据
        val callConfigBean = AppMkHelper.decodeString(AppMkHelper.CallConfigBean)
        callConfig = gson.fromJson(callConfigBean, CallConfig::class.java)
    }
    return callConfig!!
}

// 设置点击事件
fun CallActivity.setupOnClickListeners() {
    getViewBind().imDecline.setOnFastClickListener {
        handleDeclineButtonClick()
    }
    getViewBind().imAccept.setOnFastClickListener {
        handleAcceptButtonClick()
    }
}

// 处理拒绝按钮点击
private fun CallActivity.handleDeclineButtonClick() {
    if (callOperationType == CallOperationType.INCOMING_VIDEO) {
        videoCallMessage?.apply {
            getViewMode().getRefuseVideo(
                RefuseVideoRequest.newBuilder()
                    .setToUid(this.caller.uid)
                    .setChannelName(this.channelName)
                    .build()
            )
        }
    } else {
        callVideoReply?.apply {
            AgoraClient.getInstance().sendImCallMsg(this.user.uid.toString())
            if (TextUtils.isEmpty(channelName)) {
                MessageHandler.setCancelCall(this.user.uid)
            } else {
                getViewMode().setCancelCall(channelName, this.user.uid)
            }
        }
        onBackPressedCallback.handleOnBackPressed()
    }
}

// 处理接受按钮点击
private fun CallActivity.handleAcceptButtonClick() {
    if (!isVip()) {
        showToast(getString(com.example.resources.R.string.call_subscribe))
        showToast("跳转订阅商城")
        videoCallMessage?.apply {
            getViewMode().getRefuseVideo(
                RefuseVideoRequest.newBuilder()
                    .setToUid(this.caller.uid)
                    .setChannelName(this.channelName)
                    .build()
            )
        }
    } else {
        videoCallMessage?.apply {
            val isDenied = listOf(
                Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE
            ).all { XXPermissions.isGranted(this@handleAcceptButtonClick, it) }

            if (isDenied) {
                getViewMode().setAnswerVideo(this.caller.uid, this.channelName)
            } else {
                val permissingDialog = PermissingDialog(
                    this@handleAcceptButtonClick,
                    listOf(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)
                ) {
                    getViewMode().setAnswerVideo(this.caller.uid, this.channelName)
                }
                permissingDialog.show(this@handleAcceptButtonClick.supportFragmentManager, "")
            }
        }
    }
}
var playVideo: PlayVideoView? = null
// 播放视频
fun CallActivity.playVideo(url: String) {
    playVideo = PlayVideoView(this)
    getViewBind().localVideoViewContainer.addView(playVideo)
    playVideo?.setPlayUrl(url, object : Player.Listener {
        override fun onRenderedFirstFrame() {
            super.onRenderedFirstFrame()
            // 第一帧渲染回调
        }
    })
}

// 停止视频播放
fun CallActivity.stopPlay() {
    playVideo?.stopPlay()
    playVideo = null
}
